/*
 * 文件名：UpwardLawcaseController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月31日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.UpwardLawcaseAssist;
import top.infopub.mgr.la.domain.UpwardLawcaseDomain;
import top.infopub.mgr.la.service.SueLawcaseProofService;
import top.infopub.mgr.la.service.SueLawcaseService;
import top.infopub.mgr.la.service.UpwardLawcaseService;
import top.infopub.mgr.la.vo.SueLawcaseProofVo;
import top.infopub.mgr.la.vo.SueLawcaseVo;
import top.infopub.mgr.la.vo.UpwardLawcaseVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.SueLawcase;
import top.infopub.model.la.UpwardLawcaseAtt;
import top.infopub.model.la.UpwardLawcaseProof;
import top.infopub.model.la.UpwardLawcaseProofAtt;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 上诉案件申请
 * @author WuZhiyang
 * @version 2020年3月31日
 * @see UpwardLawcaseController
 * @since
 */
@Controller
@RequestMapping("/upwardLawcase")
public class UpwardLawcaseController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private SueLawcaseService sueLawcaseService;

    @Autowired
    private UpwardLawcaseService upwardLawcaseService;

    @Autowired
    private SueLawcaseProofService sueLawcaseProofService;

    /**
     * 上诉案件申请
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-upwardLawcase-list";
    }

    /**
     * 上诉案件申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<UpwardLawcaseDomain> queryDataByCondition(UpwardLawcaseVo upwardLawcaseVo,
                                                           ParamPage paramPage) {
        Page<UpwardLawcaseDomain> page = new Page<UpwardLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (upwardLawcaseVo.getEndDate() != null) {
            upwardLawcaseVo.setEndDate(DateUtils.addDays(upwardLawcaseVo.getEndDate(), 1));
        }
        //查询时，上诉申请结束日期增加一天
        if (upwardLawcaseVo.getUpwardEndDate() != null) {
            upwardLawcaseVo.setUpwardEndDate(DateUtils.addDays(upwardLawcaseVo.getUpwardEndDate(),
                1));
        }
        page = upwardLawcaseService.selectByDomainWhere(page, upwardLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 起诉案件申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<UpwardLawcaseDomain> queryMyCheckDataByCondition(UpwardLawcaseVo upwardLawcaseVo,
                                                                  ParamPage paramPage) {
        Page<UpwardLawcaseDomain> page = new Page<UpwardLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (upwardLawcaseVo.getEndDate() != null) {
            upwardLawcaseVo.setEndDate(DateUtils.addDays(upwardLawcaseVo.getEndDate(), 1));
        }
        //查询时，上诉申请结束日期增加一天
        if (upwardLawcaseVo.getUpwardEndDate() != null) {
            upwardLawcaseVo.setUpwardEndDate(DateUtils.addDays(upwardLawcaseVo.getUpwardEndDate(),
                1));
        }
        upwardLawcaseVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = upwardLawcaseService.selectMyCheckByDomainWhere(page, upwardLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 起诉案件申请-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //起诉审批通过且没有上诉审批通过的案件
        List<SueLawcase> sueLawcases = sueLawcaseService.selectNotUpwardList();
        request.setAttribute("sueLawcases", sueLawcases);
        return "la/lay-upwardLawcase-add";
    }

    /**
     * 根据id查询上诉案件申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 上诉案件申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        UpwardLawcaseVo upwardLawcaseVo = upwardLawcaseService.queryById(id);
        request.setAttribute("modelDetail", upwardLawcaseVo);
        map.put("upwardLawcaseVo", upwardLawcaseVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, upwardLawcaseVo.getProcessId());
        return new ModelAndView("la/lay-upwardLawcase-detail", map);
    }

    /**
     * 新增上诉案件申请
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(UpwardLawcaseAssist upwardLawcaseAssist) {
        
        if (upwardLawcaseAssist.getFileAtts1() == null || upwardLawcaseAssist.getFileAtts1().length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("一审判决书未上传");
        }
        
        if (upwardLawcaseAssist.getFileAtts2() == null || upwardLawcaseAssist.getFileAtts2().length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("上诉书未上传");
        }
        
        //上诉案件申请表处理
        upwardLawcaseAssist.setHrDeptId(upwardLawcaseAssist.getHrDeptid());
        upwardLawcaseAssist.setHrOrgId(upwardLawcaseAssist.getHrOrgid());
        upwardLawcaseAssist.setHrStaffApplyId(upwardLawcaseAssist.getHrStaffApplyid());
        String proCodeAndCodes = upwardLawcaseAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        upwardLawcaseAssist.setLawcaseName(split[0]);
        upwardLawcaseAssist.setSueLawcaseId(split[1]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        upwardLawcaseAssist.setId(id);
        upwardLawcaseAssist.setAddBy(vo.getId());
        upwardLawcaseAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_upward_lawcase");
        upwardLawcaseAssist.setCodes(code);
        // 处理processId
        upwardLawcaseAssist.setProcessId(IdFactory.getUUIDUpper());
        upwardLawcaseAssist.setProcessStatus("1");//审批中
        upwardLawcaseAssist.setUptBy(vo.getId());
        upwardLawcaseAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //证据清单表
        List<UpwardLawcaseProof> upwardLawcaseProofs = new ArrayList<UpwardLawcaseProof>();
        //上传附件
        List<UpwardLawcaseProofAtt> upwardLawcaseProofAtts = new ArrayList<UpwardLawcaseProofAtt>();
        String[] proofShowIdx = upwardLawcaseAssist.getProofShowIdx();
        if (proofShowIdx != null && proofShowIdx.length > 0) {
            for (int i = 0; i < proofShowIdx.length; i++ ) {
                String showIdx = proofShowIdx[i];
                String proofName = upwardLawcaseAssist.getProofName()[i];
                String proofTarget = upwardLawcaseAssist.getProofTarget()[i];
                String proofAttribute = upwardLawcaseAssist.getProofAttribute()[i];
                String numOfPage = upwardLawcaseAssist.getProofNumOfPage()[i];
                //String itemMemo = upwardLawcaseAssist.getProofItemMemo()[i];
                UpwardLawcaseProof upwardLawcaseProof = new UpwardLawcaseProof();
                String upwardLawcaseProofId = IdFactory.getUUIDUpper();
                upwardLawcaseProof.setUpwardLawcaseId(id);
                upwardLawcaseProof.setId(upwardLawcaseProofId);
                upwardLawcaseProof.setShowIdx(Integer.parseInt(showIdx));
                upwardLawcaseProof.setProofName(proofName);
                upwardLawcaseProof.setProofTarget(proofTarget);
                upwardLawcaseProof.setProofAttribute(proofAttribute);
                upwardLawcaseProof.setNumOfPage(Integer.parseInt(numOfPage));
                //upwardLawcaseProof.setItemMemo(itemMemo);
                upwardLawcaseProof.setAddBy(vo.getId());
                upwardLawcaseProof.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                upwardLawcaseProofs.add(upwardLawcaseProof);
            }

            String[] proofFileAtts = upwardLawcaseAssist.getProofFileAtts();
            String[] showIdxAtt = upwardLawcaseAssist.getShowIdxAtt();
            if (proofFileAtts != null) {
                for (int i = 0; i < proofFileAtts.length; i++ ) {
                    UpwardLawcaseProofAtt upwardLawcaseProofAtt = createFileAttProof(vo,
                        proofFileAtts[i]);
                    String showIdx = showIdxAtt[i];
                    upwardLawcaseProofAtt.setProofId(showIdx);
                    upwardLawcaseProofAtts.add(upwardLawcaseProofAtt);
                }
            }

            for (UpwardLawcaseProofAtt upwardLawcaseProofAtt : upwardLawcaseProofAtts) {
                for (UpwardLawcaseProof upwardLawcaseProof : upwardLawcaseProofs) {
                    if (upwardLawcaseProofAtt.getProofId().equals(
                        String.valueOf(upwardLawcaseProof.getShowIdx()))) {
                        upwardLawcaseProofAtt.setProofId(upwardLawcaseProof.getId());
                        break;
                    }
                }
            }
        }

        //上传附件
        List<UpwardLawcaseAtt> upwardLawcaseAtts = new ArrayList<UpwardLawcaseAtt>();
        String[] fileAtts1 = upwardLawcaseAssist.getFileAtts1();
        //附件材料
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                UpwardLawcaseAtt upwardLawcaseAtt = createFileAtt(vo, id, file);
                upwardLawcaseAtt.setTypes("1");
                upwardLawcaseAtts.add(upwardLawcaseAtt);
            }
        }

        String[] fileAtts2 = upwardLawcaseAssist.getFileAtts2();
        //附件材料
        if (fileAtts2 != null) {
            for (String file : fileAtts2) {
                UpwardLawcaseAtt upwardLawcaseAtt = createFileAtt(vo, id, file);
                upwardLawcaseAtt.setTypes("2");
                upwardLawcaseAtts.add(upwardLawcaseAtt);
            }
        }

        String[] fileAtts3 = upwardLawcaseAssist.getFileAtts3();
        //附件材料
        if (fileAtts3 != null) {
            for (String file : fileAtts3) {
                UpwardLawcaseAtt upwardLawcaseAtt = createFileAtt(vo, id, file);
                upwardLawcaseAtt.setTypes("3");
                upwardLawcaseAtts.add(upwardLawcaseAtt);
            }
        }

        upwardLawcaseService.saveUpwardLawcase(upwardLawcaseAssist, upwardLawcaseAtts,
            upwardLawcaseProofs, upwardLawcaseProofAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "法务管理 -上诉案件申请单：立案名称=" + upwardLawcaseAssist.getLawcaseName(), null);
        return RspVo.getSuccessResponse();
    }

    private UpwardLawcaseAtt createFileAtt(AuthorizationVO vo, String upwardLawcaseId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        UpwardLawcaseAtt fileAtt = new UpwardLawcaseAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setUpwardLawcaseId(upwardLawcaseId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    private UpwardLawcaseProofAtt createFileAttProof(AuthorizationVO vo, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        UpwardLawcaseProofAtt fileAtt = new UpwardLawcaseProofAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "upwardLawcaseAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询起诉案件记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUpwardLawcaseById")
    @ResponseBody
    public Map<String, Object> getUpwardLawcaseById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] split = proCodeAndCodes.split("\\_");
            SueLawcaseVo sueLawcaseVo = sueLawcaseService.queryById(split[1]);
            if (sueLawcaseVo != null) {
                List<SueLawcaseProofVo> sueLawcaseProofVos = sueLawcaseProofService.selectBySueLawcaseId(sueLawcaseVo.getId());
                if (CollectionUtils.isNotEmpty(sueLawcaseProofVos)) {
                    sueLawcaseVo.setSueLawcaseProofVos(sueLawcaseProofVos);
                }
            }
            map.put("sueLawcaseVo", sueLawcaseVo);
        }
        catch (Exception e) {
            log.error("查询起诉案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

}